/*
 * Name: DateActivity
 * Author: Sam Oakley
 * Date: 1/4/2010
 * Version Number: 1.0
 * Description: Gets all events from DB, displays them in a ListView
 * Clicking takes you to respective detail pages.
 * Changes History: 
 * 1.0 Created class
 * 1.1 Refactoring to remove redundant code from here and put it in the service
 */

package com.blork.rag;

import static android.provider.BaseColumns._ID;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class Upcoming extends ListActivity {
	
	private EventsData events;
	private SQLiteDatabase db;
	BroadcastReceiver updateReceiver;

	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upcoming); 
                        
        updateReceiver = new UpdateReceiver();
        registerReceiver(updateReceiver, new IntentFilter(EventService.ACTION_RAG_EVENT)); 
	}
    
    class UpdateReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) { 
	          Log.d(Rag.TAG, "received broadcast");
	          update();
		}
     }
    //TODO: hi
    @Override
    public void onResume(){
		super.onResume();
		update();
    }
    
    public void update(){
		setContentView(R.layout.upcoming); 
		 
		ListView lv = getListView();
		   
		lv.setTextFilterEnabled(true);
		       
		lv.setOnItemClickListener(new OnItemClickListener() {
		    public void onItemClick(AdapterView<?> parent, View view,
		        int position, long id) {
		    	onClick(position, ((TextView) view.findViewById(R.id.title)).getText());
		    }
		});
		
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		mNotificationManager.cancelAll();

		try {
			events = new EventsData(Upcoming.this);
			Cursor cursor = getEvents();
			showEvents(cursor);
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), e.toString(),
		   	          Toast.LENGTH_SHORT).show();
		}
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.layout.refresh, menu);
        return true;
    }

    /* Handles item selections */
    public boolean onOptionsItemSelected(MenuItem item) {
    	Log.d("Rag Broadcast Reciever","Starting service...");
    	startService(new Intent(Upcoming.this, EventService.class));
        return true;
    } 
    
    public void onPause(){
    	super.onPause();
    	db.close();
    }
 
    public void onDestroy(){
    	super.onDestroy();
    	unregisterReceiver(updateReceiver);
    }
    
	public void onClick(int position, CharSequence title) {
		Intent d = new Intent(this, Event.class);
		d.putExtra("title", (String)title);
		startActivity(d);
	}
	
	
	private static String[] FROM = {_ID,"title",};
	private static String ORDER_BY = "_ID DESC";
	private Cursor getEvents(){
		//Perform a managed query. The Activity will handle closing
		// and re-querying the cursor when needed.
		db=events.getReadableDatabase();
		Cursor cursor= db.query("events", FROM, null, null, null, null, ORDER_BY);
		startManagingCursor(cursor);
		return cursor;
	}

	
	private static int[] TO ={R.id.title,};
	private static String[] FROM2 = {"title",};
	private void showEvents(Cursor cursor){
		//Set up data binding
		SimpleCursorAdapter adapter= new SimpleCursorAdapter(this,
		R.layout.event_list, cursor, FROM2, TO);
		setListAdapter(adapter);
	}
}